<template>
  <div>
    <el-main>
      <!--    条件搜索      -->
      <el-form :inline="true" :model="queryDishVo" class="demo-form-inline" style="float: left;display: block">
        <el-form-item label="菜名">
          <el-input v-model="queryDishVo.name" placeholder="菜名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>

      <!--     按钮     -->
      <div style="float: right;display: block;width: 100%;text-align: left">

        <el-button type="primary" @click="addDish('add')" plain style="margin-right: 10px">新增+
          <li class="el-icon-plus"></li>
        </el-button>
        <el-button type="danger" @click="deleteBatch" plain style="margin-right: 20px">批量删除
          <li class="el-icon-delete"></li>
        </el-button>
        <!--
                <el-upload
                    action="http://localhost:8081/yum/dish/import"
                    :headers="headerObj"
                    multiple
                    :limit="3"
                    :on-success="uploadSuccess"
                    :show-file-list="false"
                    style="display: inline-block;margin-right: 20px">
                  <el-button type="info" plain>上传
                    <li class="el-icon-upload2"></li>
                  </el-button>
                </el-upload>



                <el-button type="warning" @click="exportFile" plain>下载
                  <li class="el-icon-download"></li>
                </el-button>


        -->
      </div>

      <!--    内容     -->
      <el-table
          ref="multipleTable"
          :data="tableData"

          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column

            prop="name"
            label="菜品名称"
            width="100"
            align="center">
        </el-table-column>
        <el-table-column
            prop="picture"
            label="图片"
            width="200"
            align="center">
        </el-table-column>
        <el-table-column
            prop="categoryName"
            label="菜品分类"
            width="100"
            align="center">
        </el-table-column>
        <el-table-column
            prop="price"
            label="售价"
            width="200"
            align="center">
        </el-table-column>

        <el-table-column prop="state" label="启售状态">
          <template slot-scope="scope" style="text-align: left">
            <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="switchReceiveStatus($event,scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--      分页栏-->
      <div style="margin-top: 30px;text-align: center">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="this.queryDishVo.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="this.queryDishVo.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.total">
        </el-pagination>
      </div>

      <!-- 修改弹框-->
      <el-dialog :title="title" :visible.sync="dialogFormVisible2">
        <el-form :model="dish">
          <el-form-item label="菜品名" :label-width="formLabelWidth">
            <el-input v-model="dish.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="菜品分类" :label-width="formLabelWidth" style="text-align: left">
            <el-select v-model="dish.categoryId" placeholder="请选择类别">
              <el-option v-for="(item,index) in categories" :key="index" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售价" :label-width="formLabelWidth">
            <el-input v-model="dish.price" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="submitDish2">提 交</el-button>
        </div>
      </el-dialog>

      <!--      修改新增弹窗-->

      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="dish">
          <el-form-item label="菜品名" :label-width="formLabelWidth">
            <el-input v-model="dish.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="菜品分类" :label-width="formLabelWidth" style="text-align: left">
            <el-select v-model="dish.categoryId" placeholder="请选择类别">
              <el-option v-for="(item,index) in categories" :key="index" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>


          <!--          口味-->
          <el-form-item label="口味做法配置" :label-width="formLabelWidth" style="text-align: left">
            <el-form-item>
              <div class="flavorBox">
              <span
                  v-if="dishFlavors.length == 0"
                  class="addBut"
                  @click="addFlavore"
              > + 添加口味</span>
                <div
                    v-if="dishFlavors.length != 0"
                    class="flavor"
                >
                  <div class="title">
                    <span>口味名（3个字内）</span><span>口味标签（输入标签回车添加）</span>
                  </div>
                  <div class="cont">
                    <div v-for="(item, index) in dishFlavors" :key="index" class="items">
                      <div class="itTit">
                        <div class="selectInput">
                          <div>
                            <el-input
                                v-model="item.name"
                                type="text"
                                style="width: 100%"
                                placeholder="请输入口味"
                                @focus="selectFlavor(true,index)"
                                @blur="outSelect(false,index)"
                                @input="inputHandle(index)"
                            />
                          </div>
                          <div v-show="item.showOption" class="flavorSelect">
                          <span
                              v-for="(it, ind) in dishFlavorsData"
                              :key="ind"
                              class="items"
                              @click="checkOption(it,ind,index)"
                          >{{ it.name }}</span>
                            <span
                                v-if="dishFlavorsData == []"
                                class="none"
                            >无数据</span>
                          </div>
                        </div>
                      </div>
                      <div
                          class="labItems"
                          style="display: flex"
                      >
                      <span
                          v-for="(it, ind) in item.value"
                          :key="ind"
                      >{{ it }} <i @click="delFlavorLabel(index, ind)">X</i></span>
                        <div
                            class="inputBox"
                            :style="inputStyle"
                            contenteditable="true"
                            @focus="flavorPosition(index)"
                            @keydown.enter="(val)=>keyDownHandle(val,index)"
                        ></div>
                      </div>
                      <span
                          class="delFlavor delBut non"
                          @click="delFlavor(index)"
                      >删除</span>
                    </div>
                  </div>
                  <div
                      class="addBut"
                      @click="addFlavore"
                  >
                    添加口味
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form-item>


          <!--          售价-->
          <el-form-item label="售价" :label-width="formLabelWidth">
            <el-input v-model="dish.price" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitDish">提 交</el-button>
        </div>
      </el-dialog>
    </el-main>
  </div>


</template>

<script>

export default {
  name: "DishListView",
  created() {
    this.loadData();
  },
  data() {
    return {
      tableData: [],
      currentPage1: 5,
      queryDishVo: {
        currentPage: 1,
        pageSize: 10,
        name: '',
        categoryId: "",
        price: ''
      },
      categories: [],
      total: 0,
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      formLabelWidth: '120px',
      ids: [],
      multipleSelection: [],
      op: '',
      title: '新增菜品',
      disable: false,
      headerObj: {
        Authorization: window.localStorage.getItem("Authorization")
      },
      dishFlavors: [],
      dishFlavorsData: [],
      inputStyle  : {'flex':1},
      dish: {
        name: '',
        id: '',
        price: '',
        code: '',
        image: '',
        description: '',
        flavors: [],
        status: 1,
        categoryId: ''
      }
    }
  },
  methods: {
    queryCategories() {
      this.$axios.get("/category/queryCategories").then((resp) => {
        console.log("cate", resp.data.data.categories)
        this.categories = resp.data.data.categories
      })
    },
    resetForm(){
      this.dish = {
        name: '',
        id: '',
        price: '',
        code: '',
        image: '',
        description: '',
        flavors: [],
        status: 1,
        categoryId: ''
      }
      this.dishFlavors = []
    },
    resetData() {
      this.resetForm()
      this.dialogFormVisible = false
      this.dialogFormVisible2 = false
    },

    deleteBatch() {

      if (this.ids.length) {
        this.removeMethod()
        // this.loadData()
      }
    },

    handleSelectionChange(val) {
      this.ids = []
      let _this = this
      val.forEach(function (dish) {
        _this.ids.push(dish.id)
      })
      console.log(this.ids)
      this.multipleSelection = val;
    },
    toggleSelection(rows) {
      console.log("toggle:", rows)
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleEdit(index, row) {
      console.log(index, row)
      this.dish = {
        id: row.id,
        name: row.name,
        categoryId: row.categoryId,
        price: row.price,
        status: row.status,
        flavors: [],
        description: '',
        code: '',
        image: ''

      }
      this.dialogFormVisible2 = true
      this.title = "修改信息"
      this.op = 'edit'
      this.disable = true
      // 编程式路由来进行组件跳转
      //this.$router.push({path: '/saveOrUpdate/' + row, replace: true})
    },
    handleDelete(index, row) {
      this.ids = []
      this.ids.push(row.id)
      this.removeMethod()
    },

    removeMethod() {
      this.$confirm('此操作将永久删除文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //删除请求发送
        this.$axios.get(
            '/dish/remove?ids=' + this.ids
        ).then((response) => {
          if (response.data.result) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.loadData();
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
        }).catch((reason) => {
          this.ids = []
          console.log(reason)
        })
        this.ids = []
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      }).finally(() => {
        this.ids = []
      });
    },

    handleSizeChange(val) {
      this.queryDishVo.pageSize = val
      this.loadData()
    }
    ,
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryDishVo.currentPage = val
      this.loadData()
    },
    loadData() {
      this.queryCategories();
      this.getFlavorListHand();

      let _this = this
      this.$axios.post("/dish/queryAll", this.queryDishVo).then(
          function (response) {
            if (response.data.result) {
              console.log(_this.tableData = response.data.data.pageInfo.list)
              _this.tableData = response.data.data.pageInfo.list
              _this.total = response.data.data.pageInfo.total
            } else {
              _this.$message.error(response.data.message)
            }
          }
      )
    }
    ,
    submitDish2() {

      for (let favor of this.dishFlavors){
        let valueStr = favor.value.toString()
        let tempFavor = {name:favor.name,value:'['+valueStr.substring(1,valueStr.length-1)+']'}
        this.dish.flavors.push(tempFavor)
      }

      let path = ''
      if (this.op == 'add') {
        path = "/dish/addDish"
      } else {
        path = "/dish/editDish"
      }
      let _this = this
      this.axios.post(path, this.dish).then(response => {
        console.log(response)
        if (response.data.result) {
          _this.$message.success(response.data.message);
          _this.loadData()
        } else {
          _this.$message.error(response.data.message);
        }
      })
      this.resetData()
    },
    //提交
    submitDish() {

      for (let favor of this.dishFlavors){
        let valueStr = favor.value.toString()
        let tempFavor = {name:favor.name,value:'['+valueStr.substring(1,valueStr.length-1)+']'}
        this.dish.flavors.push(tempFavor)
      }

      let path = ''
      if (this.op == 'add') {
        path = "/dish/addDish"
      } else {
        path = "/dish/editDish"
      }
      let _this = this
      this.axios.post(path, this.dish).then(response => {
        console.log(response)
        if (response.data.result) {
          _this.$message.success(response.data.message);
          _this.loadData()
        } else {
          _this.$message.error(response.data.message);
        }
      })
      this.resetData()
    },
    onSubmit() {
      console.log(1111)
      this.loadData()
    },
    addDish(op) {
      this.resetForm()
      this.op = op
      this.title = '新增菜品'
      this.dialogFormVisible = true
      this.disable = false

    },
    isOpen(row) {
      console.log(row)
      return true
    },

    //启用状态设置
    switchReceiveStatus(val, row) {
      let _this = this
      console.log(row)
      this.axios.get("/dish/setStatus/" + row.id + "/" + row.status).then(response => {
        console.log(response)
        if (response.data.result) {
          _this.$message.success("设置成功")

        } else {
          _this.$message.error("设置失败，请稍后重试")
          row.status = response.data.data.status
        }
      })
    },
    //口味---
    // 按钮 - 添加口味
    addFlavore() {
      this.dishFlavors.push({'name': '', 'value': [], showOption: false}) // JSON.parse(JSON.stringify(this.dishFlavorsData))
    },
    // 按钮 - 删除口味
    delFlavor(ind) {
      this.dishFlavors.splice(ind, 1)
    },

    // 按钮 - 删除口味标签
    delFlavorLabel(index, ind) {
      this.dishFlavors[index].value.splice(ind, 1)
    },

    //口味位置记录
    flavorPosition(index) {
      this.index = index
    },

    selectFlavor(st, index) {
      console.log('st', st)
      console.log('index', index)
      console.log('this.dishFlavors', this.dishFlavors)
      const obj = JSON.parse(JSON.stringify(this.dishFlavors[index]))
      obj.showOption = st
      this.dishFlavors.splice(index, 1, obj)
      // this.dishFlavors[index].showOption = st
    },

    checkOption(val, ind, index){
      this.selectHandle(val.name, index, ind)
      this.dishFlavors[index].name = val.name
    },

    selectHandle(val, key, ind){
      const arrDate = [...this.dishFlavors]
      arrDate[key] = JSON.parse(JSON.stringify(this.dishFlavorsData[ind]))
      this.dishFlavors = arrDate
    },

    outSelect(st, index) {
      const _this = this
      setTimeout(() => {
        const obj = JSON.parse(JSON.stringify(_this.dishFlavors[index]))
        obj.showOption = st
        _this.dishFlavors.splice(index, 1, obj)
      }, 200)
    },

    inputHandle(val, index) {
       this.selectFlavor(false,index)
    },

    // 获取口味列表
    getFlavorListHand() {
      // flavor flavorData
      this.dishFlavorsData = [
        {'name': '甜味', 'value': ['无糖', '少糖', '半糖', '多糖', '全糖']},
        {'name': '温度', 'value': ['热饮', '常温', '去冰', '少冰', '多冰']},
        {'name': '忌口', 'value': ['不要葱', '不要蒜', '不要香菜', '不要辣']},
        {'name': '辣度', 'value': ['不辣', '微辣', '中辣', '重辣']}
      ]
    },


    // 添加口味标签
    keyDownHandle(val, index) {
      console.log('keyDownHandle----val', val)
      console.log('keyDownHandle----index', index)
      console.log('keyDownHandle----this.dishFlavors', this.dishFlavors)
      if (event) {
        event.cancelBubble = true
        event.preventDefault()
        event.stopPropagation()
      }

      if (val.target.innerText.trim() != '') {
        this.dishFlavors[index].value.push(val.target.innerText)
        val.target.innerText = ''
      }
    },


  }
}

</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.selectInput {
  position: relative;
  width: 100%;
  min-width: 100px;
}
.selectInput .flavorSelect {
  position: absolute;
  width: 100%;
  padding: 0 10px;
  border-radius: 3px;
  border: solid 1px #FF903D;
  line-height: 30px;
  text-align: center;
  background: #fff;
  top: 50px;
  z-index: 99;
}
.selectInput .flavorSelect .items {
  cursor: pointer;
  display: inline-block;
  width: 100%;
  line-height: 35px;
  border-bottom: solid 1px #f4f4f4;
  color: #666;
}
.selectInput .flavorSelect .none {
  font-size: 14px;
}

#food-add-app .uploadImg .el-form-item__label::before{
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
}

.dashboard-container .container {
  background: #fff;
  position: relative;
  z-index: 1;
  padding: 30px 28px;
  border-radius: 4px;
}

.dashboard-container .container .tableBar {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}

.dashboard-container .container .tableBox {
  width: 100%;
  border: solid 2px #f3f4f7;
  border-radius: 2px;
}

.dashboard-container .container .tableBox .el-image img {
  width: 40px;
  border-radius: 5px;
}

.dashboard-container .container .pageList {
  text-align: center;
  margin-top: 30px;
}

.dashboard-container .container .tableLab .span-btn {
  cursor: pointer;
  display: inline-block;
  font-size: 14px;
  padding: 0 20px;
  color: #818693;
  border-right: solid 1px #d8dde3;
}

.dashboard-container .container .tableLab .el-button {
  margin-left: 10px;
}

.el-table-column--selection .cell {
  padding-left: 10px;
}

/* 添加 */
.addBrand-container .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.addBrand-container .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.addBrand-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}

.addBrand-container .avatar {
  width: 160px;
  height: 160px;
  display: block;
}

.addBrand-container .el-form--inline .el-form-item__content {
  width: 293px;
}

.addBrand-container .el-input {
  width: 293px;
}

.addBrand-container {
  margin: 30px;
}

.addBrand-container .container {
  position: relative;
  z-index: 1;
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  min-height: 500px;
}

.addBrand-container .container .subBox {
  padding-top: 30px;
  text-align: center;
  border-top: solid 1px #f3f4f7;
}

.flavorBox {
  width: 100%;
  float: left;

}

.flavorBox .addBut {
  background: #ffc200;
  display: inline-block;
  padding: 0px 20px;
  border-radius: 3px;
  line-height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #333333;
  font-weight: 500;
}

.flavorBox .flavor {
  border: solid 1px #dfe2e8;
  border-radius: 3px;
  padding: 15px;
  background: #fafafb;
}

.flavorBox .flavor .title {
  color: #606168;
}

.flavorBox .flavor .cont .items {
  display: flex;
  margin: 10px 0;
}

.flavorBox .flavor .cont .items .itTit {
  width: 150px;
  margin-right: 15px;
}

.flavorBox .flavor .cont .items .itTit input {
  width: 100%;
  line-height: 40px;
  border-radius: 3px;
  padding: 0 10px;
}

.flavorBox .flavor .cont .items .labItems {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  border-radius: 3px;
  min-height: 39px;
  border: solid 1px #d8dde3;
  background: #fff;
  padding: 0 5px;
}

.flavorBox .flavor .cont .items .labItems span {
  display: inline-block;
  color: #f19c59;
  margin: 5px;
  line-height: 26px;
  height: 26px;
  padding: 0 10px;
  background: #fdf4eb;
  border-radius: 3px;
  border: solid 1px #fae2cd;
}

.flavorBox .flavor .cont .items .labItems span i {
  cursor: pointer;
  font-style: normal;
}

.flavorBox .flavor .cont .items .labItems .inputBox {
  display: inline-block;
  width: 100%;
  height: 36px;
  line-height: 36px;
  overflow: hidden;
}

.flavorBox .flavor .cont .items .delFlavor {
  display: inline-block;
  padding: 0 10px;
  color: #f19c59;
  cursor: pointer;
}

.addBrand-container .address .el-form-item__content {
  width: 777px !important;
}

.el-button--text {
  font-weight: 400 !important;
  font-size: 13px !important;
}

.el-table td {
  font-size: 13px !important;
}

.el-table .cell,
.el-table th div,
.el-table--border td:first-child .cell,
.el-table--border th:first-child .cell {
  padding-left: 12px;
}


</style>
